import copy
from stingingnettlepy import dict_functions

def create_navigation( node, max_lvl = -1, cur_lvl = 0, path = "/" ):
	"""Returns the generated navigation as HTML code.

	node is the site_structure or a part of it.

	"""
	HTML = "<ul class='mainnavigation'>"
	
	for key, value in node.items():

		# We only need the name of the page.
		if ":" in key:
			pagename = key.split( "template:" )[0].strip()
		else:
			pagename = key.strip()


		


		HTML += "<li><a href='%s'>%s</a></li>" % ( path + pagename.replace( " ", "_" ), pagename )

#		if len( value ) > 0:
#			if max_lvl == -1:
#				HTML += "<li>"
#				HTML += create_navigation( value, max_lvl, cur_lvl, path + pagename.replace( " ", "_" ) + "/" )
#				HTML += "</li>"
#
#			elif max_lvl > cur_lvl:
#				HTML += "<li>"
#				HTML += create_navigation( value, max_lvl, cur_lvl + 1, path + pagename.replace( " ", "_" ) + "/" )
#				HTML += "</li>"

	HTML += "</ul>"

	return HTML


def create_main_navigation( node, max_lvl = -1 ):
	return create_navigation( node, max_lvl )


def create_sub_navigation( entire_node, page_id, page_name, part_of_root_path, start_lvl = -1, end_lvl = -1 ):
	"""node represents the entire website structure.

	"""
	result = []
	path = []

	if ":" in page_name:
		page_name = page_name.split( "template:" )[0].strip()


	# Get the parent if there is one.
	def get_parent( d, page_id, count = 1 ):
		for k, v in d.items():
			if isinstance( v, dict ):
				res = get_parent( v, page_id, count + 1 )
			

	def get_keys(d, target, path ):
		for k, v in d.items():
			path.append(k)
			result.append(copy.copy(path))
			if len( v ) > 0:
				#result.append(copy.copy(path))
				get_keys(v, target, path )
				path.pop()
			else:
				path.pop()

	get_keys( entire_node, page_name.replace( "_", " " ), path )

	page_nodepath = result[page_id-1]

	# The parent node.
	if len( result[page_id-1] ) - 1 == 0:
		parent_node = None
	else:
		parent_node = result[page_id-1][len( result[page_id-1] )-2]

	# Sibling nodes.
	siblings = []

	if len( page_nodepath ) == 1:
		for t in filter( lambda x: len( x ) == 1, result ):
			siblings.append( t[0] )
	else:
		for t in filter( lambda x: len ( x ) == len( page_nodepath ) and page_nodepath[len( page_nodepath ) -2] == x[len( x ) -2 ], result ):
			siblings.append( t[-1] )
			
	# Child nodes.
	children = []

	for res in result:
		if len( res ) - 1 == len( page_nodepath ) and set( res[0:-1] ) == set( page_nodepath ):
			set1 = set( page_nodepath )
			other = set( res )

			for x in other.difference( set1 ):
				if "template:" in x:
					z = x.split( "template:" )[0].strip()
				else:
					z = x
				children.append( z )


	# Create the .html code.
	if parent_node is None:
		
		HTML = ""
		if len( siblings ) > 0:
			HTML += "<ul class='subnavigation_parent'>"
			for x in siblings:
				if x == page_name.replace( "_", " " ):
					link_active_class = "class='link_active'"
				else:
					link_active_class = ""
					
				HTML += "<li %s><a href='%s'>%s</a></li>" % ( link_active_class, "/" + x.replace( " ", "_" ), x )
				if x == page_name.replace( "_", " " ):
					if len( children ) > 0:
						HTML += "<li><ul class='subnavigation_children'>"
						for y in children:
							HTML += "<li><a href='%s'>%s</a></li>" % ( "/" + page_name.replace( " ", "_" ) + "/" + y.replace( " ", "_" ), y )
						HTML += "</ul></li>"
			HTML += "</ul>"	

	else:
		HTML = "<ul class='subnavigation_parent'><li><a href='%s'>%s</a></li>" % ( part_of_root_path, parent_node )
		if len( siblings ) > 0:
			HTML += "<li><ul class='subnavigation_siblings'>"
			
			for x in siblings:
				if x == page_name:
					link_active_class = "class='link_active'"
				else:
					link_active_class = ""
								
				HTML += "<li %s><a href='%s'>%s</a></li>" % ( link_active_class, part_of_root_path + "/" + x.replace( " ", "_" ), x )
				if x == page_name.replace( "_", " " ):
					if len( children ) > 0:
						HTML += "<li><ul class='subnavigation_children'>"
						for y in children:
							HTML += "<li><a href='%s'>%s</a></li>" % ( part_of_root_path + "/" + page_name + "/" + y.replace( " ", "_" ), y )
						HTML += "</ul></li>"
			HTML += "</ul></li>"
		HTML += "</ul>"
		
	return HTML


def build_links( complete_node, parent_node = "", links = [] ):
	for key, value in complete_node.items():
		links.append( parent_node + "/" + key.replace( " ", "_" ) )
		parent = parent_node + "/" + key.replace( " ", "_" )
		if len( value ) > 0:
			links = build_links( value, parent.replace( " ", "_" ), links )

	return links


def build_page_links( relpath ):
	"""Builds links for a single page
	Returns a list  containing the links.
	
	"""
	links = []
	relpath_parts = relpath.split( "/" )[1:]
	cur_relpath = ""
	for x in relpath_parts:
		cur_relpath += x
		links.append( cur_relpath )
		
	return links


def create_sub_navigation3( links, relpath, root_node ):
	"""
	"""
	HTML = "<ul>"
	for link in links:
		if link.startswith( relpath ):
			HTML += "<li><a href='%s'>%s</a></li>" % ( link, link.split("/")[-1] )
	HTML += "</ul>"
	return HTML

def create_sub_navigation2( complete_node, relpath, cur_path, counter, link = "/" ):
	HTML = "<ul>"
	relpath = "/" + relpath
	links = build_links( complete_node, "", [] )
	deeper = False
	
	additional_html = ""
	len_last_parts = 0
	for link in links:
		if link.startswith( "/" + relpath.split( "/" )[1] ):
			len_last_parts = len( link.split( "/" ) ) - 1
			break
	
	for link in links:
		if link.startswith( "/" + relpath.split( "/" )[1] ):
			test1 = link.split( "/" )
			test1 = "/".join( test1[:-1] )
#			if len( link.split( "/" ) ) >= 3 and not relpath.startswith( test1 ):
#				continue
#			if len( link.split( "/" ) ) - len( relpath.split( "/" ) ) > 1:
#				continue
#			elif len( link.split( "/" ) ) > 3 and not relpath.startswith( link ):
#				print( link)
#				print( relpath )
#				continue
			# This link belongs to this page.
			# Determine whether the link is a link to the parent of the current page, a sibling or the page itself, or a child of the current page.
			link_parts = len( link.split( "/" ) ) - 1
			relpath_parts = len( relpath.split( "/" ) ) -1
			
			if len( link.split( "/" ) ) >= 3 and not relpath.startswith( test1 ):
				continue
			
			if len_last_parts < link_parts:
				# Start of a new unordered list.
				HTML += "<li><ul>"
				deeper = True
			elif len_last_parts > link_parts:
				# End of a new unordered list.
				difference = len_last_parts - link_parts
				HTML += "</ul></li>" * difference
			else:
				additional_html = ""
			
			
			HTML += "<li><a href='%s'>%s</a></li>\n" % ( link, link.split( "/" )[-1] )
			
			len_last_parts = copy.deepcopy( link_parts )
	
	if deeper:
		HTML += "</ul></li></ul>"
	else:
		HTML += "</ul>"
	return HTML
